package com.ramnight.unify.boot.s3;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.util.IOUtils;
import com.ramnight.unify.kit.exception.UnifyException;

public class UnifyS3 {
	private AmazonS3 s3;

	public UnifyS3(AmazonS3 s3) {
		this.s3 = s3;
	}
	
	public void upload(String bucket, MultipartFile file) {
		String fileName = file.getOriginalFilename();
		upload(bucket, fileName, file);
	}

	// 不能有中文名
	public void upload(String bucket, String fileName, MultipartFile file) {
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentType(file.getContentType());
		objectMetadata.setContentLength(file.getSize());
		try {
			PutObjectRequest request = new PutObjectRequest(bucket, fileName, file.getInputStream(), objectMetadata)
					// 设置文件访问权限，bucket所有者可以看到，默认仅上传账号能看到
					.withCannedAcl(CannedAccessControlList.BucketOwnerFullControl);
			s3.putObject(request);
		} catch (Exception e) {
			throw new UnifyException(e);
		}
	}

	// 不能有中文名
	public ResponseEntity<byte[]> download(String bucket, String name) {
		GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, name);
		try {
			S3Object s3Object = s3.getObject(getObjectRequest);
			S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
			byte[] bytes = IOUtils.toByteArray(objectInputStream);
			// 替换中文
			// name = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			httpHeaders.setContentLength(bytes.length);
			httpHeaders.setContentDispositionFormData("attachment", name);
			return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
		} catch (Exception e) {
			throw new UnifyException(e);
		}
	}
}
